package com.openvalley.cyj.synergy.pojo;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.*;

/**
 * 存根，远程通讯时本地的代理类
 */
public class MyRemoteProxy implements IRemoteBroker {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00001, MyRemoteProxy.class.getSimpleName());

    public static final int DATACODE = 0x001;
    //请求的token
    public static final String DATAINTERFACETOKEN = "null";
    //响应的token
    public static final String REPLYINTERFACETOKEN = "404";

    private IRemoteObject remoteObject = null;
    public MyRemoteProxy(IRemoteObject iRemoteObject){
        this.remoteObject = iRemoteObject;
    }

    @Override
    public IRemoteObject asObject() {
        return null;
    }

    /**
     * 此处定义的方法，此方法将来由远程调用
     * @param a
     * @param b
     * @return
     * @throws RemoteException
     */
    public int add(int a, int b) throws RemoteException {
        MessageParcel data = MessageParcel.obtain();
        MessageParcel reply = MessageParcel.obtain();
        MessageOption messageOption = new MessageOption(MessageOption.TF_SYNC);

        int result = 0;
        try{
            //往请求中写入数据
            data.writeInterfaceToken(DATAINTERFACETOKEN);
            data.writeInt(a);
            data.writeInt(b);

            // 请求码 请求 响应 可选性
            remoteObject.sendRequest(DATACODE, data, reply, messageOption);

            //从响应中获得数据
             String interfaceToken = reply.readInterfaceToken();
             if(REPLYINTERFACETOKEN.equals(interfaceToken)){
                 //如果token匹配
                 result = reply.readInt();
             }
        }finally {
            data.reclaim();
            reply.reclaim();
        }
       return result;
    }
}
